package chaowan.Service.impl;
import chaowan.Mapper.GoodsMapper;
import chaowan.Mapper.UserCartMapper;
import chaowan.Service.UserCartService;
import chaowan.pojo.CartVO;
import chaowan.pojo.Goods;
import chaowan.pojo.UserCart;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserCartServiceImpl implements UserCartService {

    @Resource
    private UserCartMapper userCartMapper;

    @Override
    public List<UserCart> getAllCarts() {
        return userCartMapper.selectAll();
    }

    @Override
    public UserCart getCartById(Long cartId) {
        return userCartMapper.selectById(cartId);
    }

    @Override
    public int save(UserCart userCart) {
        return userCartMapper.insert(userCart);
    }

    @Override
    public int update(UserCart userCart) {
        return userCartMapper.update(userCart);
    }

    @Override
    public int deleteById(Long cartId) {
        return userCartMapper.deleteById(cartId);
    }

    @Override
    public void addToCart(Long uid, Long gid) {
        UserCart cart = userCartMapper.findByUserAndGoods(uid, gid);
        if (cart != null) {
            cart.setCount(cart.getCount() + 1);
            userCartMapper.update(cart);
        } else {
            UserCart newCart = new UserCart();
            newCart.setUserId(uid);
            newCart.setGoodsId(gid);
            newCart.setCount(1);
            newCart.setChecked(0);
            userCartMapper.save(newCart);
        }
    }

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public List<CartVO> getCartVOsByUserId(Long uid) {
        List<UserCart> carts = userCartMapper.selectByUserId(uid);
        List<CartVO> result = new ArrayList<>();

        for (UserCart cart : carts) {
            Goods goods = goodsMapper.selectById(cart.getGoodsId());
            if (goods != null) {
                CartVO vo = new CartVO();
                vo.setUserId(cart.getUserId());
                vo.setCartId(cart.getCartId());
                vo.setGoodsId(goods.getGid());
                vo.setGoodsName(goods.getName());
                vo.setCoverUrl(goods.getCoverUrl());
                vo.setPrice(goods.getPrice());
                vo.setCount(cart.getCount());
                vo.setChecked(cart.getChecked());
                result.add(vo);
            }
        }

        return result;
    }
}